﻿using SqlSugar;
using WeDonekRpc.SqlSugar.Tran;

namespace WeDonekRpc.SqlSugar
{
    internal class SqlClientFactory : ISqlClientFactory
    {
        private readonly IDBConfig _Config;
        private SqlSugarClient _DbClient;

        [System.ThreadStatic]
        private static ILocalTran _Current = null;

        public SqlClientFactory (IDBConfig config)
        {
            this._Config = config;
        }
        protected SqlSugarClient DbClient
        {
            get
            {
                if (this._DbClient == null)
                {
                    this._DbClient = new SqlSugarClient(this._Config.Configs);
                }
                return this._DbClient;
            }
        }
        public bool IsTran => _Current != null;

        public ILocalTran Current { get => _Current; }

        public void BeginTran ()
        {
            _Current = new LocalTran(this.DbClient);
            _Current.BeginTran();
        }
        public void CommitTran (ILocalTran client)
        {
            if (_Current != null)
            {
                _Current.CommitTran();
                _Current = client;
            }
        }
        public void RollbackTran (ILocalTran client)
        {
            if (_Current != null)
            {
                _Current.RollbackTran();
                _Current = client;
            }
        }
        public SqlSugarProvider GetProvider (string name)
        {
            if (_Current != null)
            {
                return _Current.GetProvider(name);
            }
            return this.DbClient.GetConnection(name);
        }



        public ISugarQueryable<T> GetQueryable<T> (string name)
        {
            return this.DbClient.GetConnection(name).Queryable<T>();
        }

        public static void PendingTran (ILocalTran tran)
        {
            if (_Current != null && _Current.TranId == tran.TranId)
            {
                _Current = null;
            }
        }

        public void Dispose ()
        {
            if (_Current != null)
            {
                _Current.Dispose();
                _Current = null;
            }
        }
    }
}
